<script setup lang="ts">
import {reactive, onMounted, nextTick, ref, defineAsyncComponent} from 'vue';
import {
  getWashOrderList,
  postWashOrderList
} from '/@/api/api'
const TablePrint = defineAsyncComponent(() => import('./tablePrint.vue'))
const tablePrintRef = ref();
import {ElMessage} from 'element-plus';
import {formatTime} from "/@/utils";
import {useRoute} from 'vue-router';
import mittBus from '/@/utils/mitt';
const route = useRoute()
const avueFormRes = ref()
const data = reactive({
  title:'Add',
  dialogShow: false,
  tabIndex: 0,
  dataList: [],
  page: {
    total: 10,
    currentPage: 1,
    pageSize: 10,
  },
  option: {
    searchLabelWidth: 50,
    selection:true,
    addBtn: false,
    printBtn: false,
    excelBtn: false,
    // searchSpan: 5,
    searchMenuSpan: 4,
    border: true,
    viewBtn: false,
    editBtn: false,
    delBtn: false,
    align: 'center',
    column: [
      {
        label: 'Start time',
        prop: 'createTime',
        minWidth: 150,
        search: true,
        searchType: 'daterange',
        searchSpan: 12,
        searchLabel: 'Time'
      },
      {
        label: 'Order number',
        prop: 'orderNum',
      },
      {
        label: 'Phone',
        prop: 'userPhone',
        search: true,
        searchLabelWidth:100,
      },
      {
        label: 'User code',
        prop: 'userCode',
      },
      {
        label: 'Order status',
        prop: 'dryStart',
        search: true,
        searchLabelWidth:100,
        searchSpan: 6,
        searchType: 'select',
        dicData: [
          {
            label: 'incompletion',
            value: 0,
          },
          {
            label: 'Done',
            value: 1,
          }
        ],
      },
      {
        label: 'Order type',
        prop: 'dryType',
        search: true,
        searchLabelWidth:100,
        searchSpan: 6,
        searchType: 'select',
        dicData: [
          {
            label: 'Wash & Fold',
            value: 0,
          },
          {
            label: 'Dry Cleaning',
            value: 1,
          },
          {
            label: 'Request Delivery',
            value: 2,
          }
        ],
      },
      {
        label: 'Request delivery',
        prop: 'isDeliver',
        search: true,
        searchLabelWidth:140,
        searchSpan: 6,
        searchType: 'select',
        dicData: [
          {
            label: 'NO',
            value: 0,
          },
          {
            label: 'Yes',
            value: 1,
          },
        ],
      },
      {
        label: 'Urgent',
        prop: 'isUrgent',
        search: true,
        searchLabelWidth:100,
        searchSpan: 6,
        searchType: 'select',
        dicData: [
          {
            label: 'NO',
            value: 0,
          },
          {
            label: 'Yes',
            value: 1,
          },
        ],
      },
      {
        label: 'Request a delivery time',
        prop: 'deliverTime',
      },
      {
        label: 'Pick-up time',
        prop: 'deliveryTime',
      },
    ]
  },
  optionForm: {
    submitText:'Submit',
    emptyText	:'Empty',
    column: [
      {
        label: 'Sort',
        span: 24,
        prop: 'sort',
        type: 'number',
        rules: [
          {
            required: true,
            message: "Please enter the order",
            trigger: "blur"
          }
        ]
      },
      {
        label: 'Label name',
        span: 24,
        prop: 'labelName',
        type: 'input',
        labelWidth:120,
        rules: [
          {
            required: true,
            message: "Please enter a name for the label",
            trigger: "blur"
          }
        ]
      }
    ]
  },
  form: {},
  formSearch:{
    userPhone:'',
    dryType:null
  },
  curriculumForm:{
    courseName:'',
    loading:false,
    options:[],
    item:{}
  },
  selectionList:[]
})

onMounted(() => {
  if(route.query.orderNum){
    bannerList({orderNum:route.query.orderNum})
  }
  mittBus.on('messageread', () => {
    bannerList()
  })
})
const bannerList = (row:object = {}) => {
  let page = {
    pageIndex: data.page.currentPage,
    pageSize: data.page.pageSize
  }
  getWashOrderList({...page,...row}).then((res: any) => {
    if (res.code === 200) {
      data.dataList = res.data.list
      data.page.total = res.data.total
    }

  })
}

const onLoad = (e:any) => {
  console.log(e)
  data.page.currentPage = e.currentPage
  data.page.pageSize = e.pageSize
  bannerList()
}
const refreshChange = () => {
  bannerList()
}
const Complete = (row:any) => {
  postWashOrderList({dryOrderId:row.dryOrderId}).then((res:any)=>{
    if(res.code === 200){
      ElMessage({
        showClose: true,
        message: 'Operation Success',
        type: 'success',
      })
    }
    bannerList()
  })
}
const printFun = (val:any) => {
  tablePrintRef.value.initComponent([val]);
}
const resetChange = (item: any) => {
  data.formSearch.userPhone = ''
  data.formSearch.dryType = null
  bannerList()
}
const searchChange = (params: any, done: any) => {
  console.log(params)
  delete params.userPhone
  done()
  data.formSearch = {
    ...data.formSearch,
    ...params
  }
  bannerList({
    startTime: data.formSearch.createTime ? formatTime(data.formSearch.createTime[0], 'YYYY-MM-DD') : '',
    endTime: data.formSearch.createTime ? formatTime(data.formSearch.createTime[1], 'YYYY-MM-DD') : '',
    userPhone: data.formSearch.userPhone,
    dryType:data.formSearch.dryType,
    ...params
  })
}
const formatPhoneNumber = (phoneNumber:any) => {
  const cleanedInput = phoneNumber.replace(/[^0-9]/g, '');
  if (cleanedInput.length !== 10) {
    return phoneNumber;
  }

  const formattedNumber = `${cleanedInput.slice(0, 3)}-${cleanedInput.slice(3, 6)}-${cleanedInput.slice(6)}`;
  return formattedNumber;
}
const selectionChange = (list) => {
  data.selectionList = list
}
const batchPrint = () => {
  if (data.selectionList.length === 0){
    ElMessage({
      showClose: true,
      message: 'Please select the order',
      type: 'warning',
    })
    return
  }
  tablePrintRef.value.initComponent(data.selectionList);
}
const selectChange = (value:any) => {
  bannerList({dryType:value})
  // console.log(value)
}
</script>

<template>
  <div class="layout-pd">
    <div class="carousel-box">
      <avue-crud v-model:page="data.page" :data="data.dataList" :option="data.option"
                 @selection-change="selectionChange"
                 @on-load="onLoad" @search-reset="resetChange" @refresh-change="refreshChange" @search-change="searchChange"  >
        <template #menu-left="{}">
          <el-button type="primary" @click="batchPrint">Batch print</el-button>
        </template>
        <template #userPhone-search="{disabled,size}">
          <el-input
              v-model="data.formSearch.userPhone"
              placeholder="Please enter a phone number"
              :maxlength="12"
              :formatter="(value) => (value ? formatPhoneNumber(value) : '')"
          />
        </template>
        <template #dryType-search="{disabled,size}">
          <el-select
              v-model="data.formSearch.dryType"
              placeholder="Select"
              @change="selectChange"
          >
            <el-option :key="0" label="Wash & Fold" :value="0"/>
            <el-option :key="1" label="Dry Cleaning" :value="1"/>
            <el-option :key="2" label="Request Delivery" :value="2"/>
          </el-select>
        </template>
        <template #menu="{row}">
          <el-button v-if="row.dryStart === 0" text type="primary" @click="Complete(row)">Complete</el-button>
          <el-button text type="primary" @click="printFun(row)">Print</el-button>
        </template>
      </avue-crud>
    </div>
    <tablePrint ref="tablePrintRef"/>
  </div>
</template>

<style scoped lang="scss">
.carousel-box {
  width: 100%;
  box-sizing: border-box;
  background: var(--el-color-white);
  padding: 20px;
}

.item-img {
  width: 100%;

  img {
    width: 50%;
  }
}

::v-deep .avue-form__row {
  margin-bottom: 20px;
}
::v-deep .el-select {
  width: 100% !important;
}
</style>